package com.daka.controller;

import com.daka.entity.AuctionTradeList;
import com.daka.entity.Goods;
import com.daka.entity.User;
import com.daka.entity.UserOpen;
import com.daka.enumerate.StatusCode;
import com.daka.service.AuctionTradeListService;
import com.daka.service.GoodsService;
import com.daka.service.UserOpenService;
import com.daka.service.UserService;
import com.daka.tools.AuctionEndLine;
import com.daka.tools.DateUtil;
import com.daka.tools.Identities;
import com.daka.tools.SessionHolder;
import com.daka.vo.BaseResponseVo;
import com.daka.vo.DataResponseVo;
import com.daka.vo.request.UserAuctionVo;
import com.daka.vo.response.GoodsVo;
import com.daka.vo.response.IndexGoodsVo;
import com.daka.vo.response.OffLineGoodsList;
import com.daka.vo.response.PriceListVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yangx
 * CreateTime: 2016/12/28 18:55
 */

@Controller
@RequestMapping("/auctionIndex")
@Slf4j
public class AucTionController {

    @Resource
    private GoodsService goodsService;
    @Resource
    private AuctionTradeListService auctionTradeListService;
    @Resource
    private UserService userService;
    @Resource
    private UserOpenService userOpenService;

    @RequestMapping(method = RequestMethod.POST, value = "/queryList")
    @ResponseBody
    public Object queryList(HttpServletResponse response) {
        //拍品列表
//        List<Goods> list = goodsService.selectAll();
        List<Goods> list = goodsService.selectA();
        List<Goods> list1 = goodsService.selectB();
        for (Goods goods : list1) {
            list.add(goods);
        }

        List<IndexGoodsVo> retList = new ArrayList<>();
        for (Goods goods : list) {
            retList.add(IndexGoodsVo.build(goods));
        }
        //总金额
        BigDecimal totalMoney = goodsService.sumTotal();
        if (totalMoney == null) {
            totalMoney = new BigDecimal("0.00");
        }
        //竞拍总次数
        int count = auctionTradeListService.countAll();

        Long thisTime = new Date().getTime();
        Long endTime = DateUtil.str2Date(AuctionEndLine.AUCTION_END_TIME, DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS).getTime();
        long time = endTime - thisTime;
        if (time < 0) {
            time = 0;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("retList", retList);
        map.put("totalMoney", totalMoney);
        map.put("count", count);
        map.put("time", BigDecimal.valueOf(time).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_DOWN));
        return new DataResponseVo<Object>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), map);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/queryDetail")
    @ResponseBody
    public DataResponseVo<Object> queryDetail(@RequestBody Goods param) {
        //拍品详情
//        Goods goods = goodsService.selectById(param.getId());
        Goods goods = goodsService.selectByCode(param.getCode());
        if (goods == null) {
            return new DataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }
        //拍价列表
        List<AuctionTradeList> list = auctionTradeListService.selectAllByGoods(goods.getId());
        List<PriceListVo> listPrice = new ArrayList<>();
        int a = 0;
        for (AuctionTradeList auctionTradeList : list) {
            PriceListVo priceListVo = new PriceListVo();
            priceListVo.setPrice(auctionTradeList.getAmount());
            priceListVo.setNumber(list.size() - a);
            listPrice.add(priceListVo);
            a = a + 1;
            if (listPrice.size() > 9) {
                break;
            }
        }

        Long thisTime = new Date().getTime();
        Long endTime = DateUtil.str2Date(AuctionEndLine.AUCTION_END_TIME, DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS).getTime();
        long time = endTime - thisTime;
        if (time < 0) {
            time = 0;
        }

        Map<String, Object> map = new HashMap<>();
        GoodsVo goodsVo = GoodsVo.build(goods);
        User user = userService.selectById(goods.getMaxUser());
        if (user != null) {
            goodsVo.setMaxUserStr(user.getName());
        }
        map.put("goods", goodsVo);
        map.put("listPrice", listPrice);
        map.put("time", BigDecimal.valueOf(time).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_DOWN));
        return new DataResponseVo<Object>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), map);
    }

    //下单
    @RequestMapping(method = RequestMethod.POST, value = "/createAuction")
    @ResponseBody
    public synchronized BaseResponseVo createAuction(@RequestBody UserAuctionVo userAuctionVo) {
        Long thisTime = new Date().getTime();
        Long endTime = DateUtil.str2Date(AuctionEndLine.AUCTION_END_TIME, DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS).getTime();
        long time = endTime - thisTime;
        if (time < 0) {
            return new DataResponseVo<>(StatusCode.AUCTION_TIME_OUT.getCode(), StatusCode.AUCTION_TIME_OUT.getMessage());
        }

        Goods goods = goodsService.selectByCode(userAuctionVo.getGoodsCode());

        if (userAuctionVo.getAmount() == null) {
            return new DataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }
        String openId = SessionHolder.getOpenId();
        if (openId == null) {
            return new DataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }
        UserOpen userOpen = userOpenService.selectByOpenId(openId);
        User user = userService.selectById(userOpen.getUserId());

        if (userAuctionVo.getAmount().compareTo(goods.getMaxAmount()) != 1) {
            return new BaseResponseVo(StatusCode.PRICE_NOT_MAX.getCode(), StatusCode.PRICE_NOT_MAX.getMessage());
        }
        AuctionTradeList auctionTradeList = new AuctionTradeList();
        auctionTradeList.setPayType(1);
        auctionTradeList.setPayStatus(0);
        auctionTradeList.setUser(user.getId());
        auctionTradeList.setTeam(user.getTeam());
        auctionTradeList.setAmount(userAuctionVo.getAmount());
        auctionTradeList.setAuctionStatus(0);
        auctionTradeList.setGoods(goods.getId());
        auctionTradeList.setPayFlag(0);
        auctionTradeList.setCode(Identities.randomBase62(6));
        auctionTradeList.setCreateTime(new Date());
        auctionTradeListService.insert(auctionTradeList);

        goods.setMaxAmount(userAuctionVo.getAmount());
        goods.setMaxTeam(user.getTeam());
        goods.setMaxUser(user.getId());
        goods.setUpdateTime(new Date());
        goodsService.updateByPrimaryKeySelective(goods);
        return new BaseResponseVo(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
    }

    /**
     * 订单补录
     */
    @RequestMapping(method = RequestMethod.POST, value = "/addAuction")
    @ResponseBody
    public BaseResponseVo addAuction(@RequestBody UserAuctionVo userAuctionVo) {

        Goods goods = goodsService.selectByCode(userAuctionVo.getGoodsCode());

//        if (userAuctionVo.getAmount().compareTo(goods.getMaxAmount()) <= 0){
//            return new BaseResponseVo(StatusCode.SERVER_EXCEPTION.getCode(), "明拍/快拍线下拍卖金额不能小于线上拍卖金额");
//        }

        if (null == userAuctionVo.getUserId() || 0 == userAuctionVo.getUserId()) {
            AuctionTradeList auctionTradeList = new AuctionTradeList();
            auctionTradeList.setPayType(2);
            auctionTradeList.setUser(userAuctionVo.getUserId());
            auctionTradeList.setTeam(userAuctionVo.getTeamId());
            auctionTradeList.setPayStatus(1);
            auctionTradeList.setAmount(userAuctionVo.getAmount());
            auctionTradeList.setAuctionStatus(0);
            auctionTradeList.setCode(RandomStringUtils.random(6));
            auctionTradeList.setCreateTime(new Date());
            auctionTradeList.setGoods(goods.getId());
            auctionTradeList.setPayFlag(0);
            auctionTradeListService.insert(auctionTradeList);

            goods.setMaxAmount(userAuctionVo.getAmount());
            goods.setMaxTeam(userAuctionVo.getTeamId());
            goods.setMaxUser(userAuctionVo.getUserId());
            goodsService.updateByPrimaryKeySelective(goods);
        } else {
            User user = new User();
            user.setMobile(userAuctionVo.getMobile());
            user.setName(userAuctionVo.getUserName());
            user.setTeam(-1l);
            user.setStatus("1");
            user.setCreateTime(new Date());
            user.setCreateUser("Admin");
            userService.save(user);

            AuctionTradeList auctionTradeList = new AuctionTradeList();
            auctionTradeList.setPayType(2);
            auctionTradeList.setUser(user.getId());
            auctionTradeList.setTeam(user.getTeam());
            auctionTradeList.setPayStatus(1);
            auctionTradeList.setAmount(userAuctionVo.getAmount());
            auctionTradeList.setAuctionStatus(0);
            auctionTradeList.setCode(RandomStringUtils.random(6));
            auctionTradeList.setCreateTime(new Date());
            auctionTradeList.setGoods(goods.getId());
            auctionTradeList.setPayFlag(0);
            auctionTradeListService.insert(auctionTradeList);

            goods.setMaxAmount(userAuctionVo.getAmount());
            goods.setMaxTeam(userAuctionVo.getTeamId());
            goods.setMaxUser(userAuctionVo.getUserId());
            goodsService.updateByPrimaryKeySelective(goods);
        }
        return new BaseResponseVo(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
    }

    @RequestMapping(method = RequestMethod.POST, value = "/findOffline")
    @ResponseBody
    public DataResponseVo<OffLineGoodsList> findOffline() {
        OffLineGoodsList offLineGoodsList = goodsService.findOffLineGoods();

        return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), offLineGoodsList);
    }
}
